/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include "pit.h"

#include <kerneldebugconsole.h>

/**
 * Hundred hertz frequency.
 */
#define PIT_FREQUENCY 100

PLPit::PLPit() : m_IoPort("PIT"), m_IrqId(0), m_Handler(0) {
}

bool PLPit::registerHandler(PLTimerHandler *handler) {
	if(handler == 0 && m_Handler != 0) {
		return false;
	}
	m_Handler = handler;
	return true;
}

bool PLPit::start() {
	if(m_IoPort.allocate(0x40, 4) == false) {
		return false;
	}
	PLIrqManager *irqManager = PLProcessor::instance().irqManager();
	m_IrqId = irqManager->registerIsaIrqHandler(0, this, true);
	if(m_IrqId == 0) {
		return false;
	}
	// Set the PIT frequency
	// The value we send to the PIT is the value to divide it's input clock
	// (1193180 Hz) by, to get our required frequency. Important to note is
	// that the divisor must be small enough to fit into 16-bits.
	size_t divisor = 1193180 / PIT_FREQUENCY;
	m_IoPort.write8(0x36, 3);
	// Divisor has to be sent byte-wise, so split here into upper/lower bytes.
	uint8_t l = divisor & 0xFF;
	uint8_t h = (divisor>>8) & 0xFF;
	// Send the frequency divisor.
	m_IoPort.write8(l, 0);
	m_IoPort.write8(h, 0);
	return true;
}

bool PLPit::irq(uint8_t /*number*/, InterruptState &state) {
	if(m_Handler != 0) {
		m_Handler->timer(0, state);
	}
	return true;
}
